import tkinter as tk
import json
import random
from tkinter.constants import LEFT

top = tk.Tk()
data = []

with open(file = 'test1.json', mode = 'r', encoding = 'utf8') as f: #读入文档
    ftext = f.read()
data = json.loads(ftext)  
    
frame1 = tk.Frame()
frame1.pack()
frame2 = tk.Frame()
frame2.pack()
lb1 = tk.Label(frame1,text = '题目数量：')
lb1.pack(side=tk.LEFT)
n = tk.IntVar()
m = tk.StringVar()
entry1 = tk.Entry(frame1,textvariable=n)
entry1.pack(side=tk.LEFT)

lb2 = tk.Label(frame2,text = "搜索题目：")
lb2.pack(side=tk.LEFT)
entry2 = tk.Entry(frame2,textvariable=m)
entry2.pack(side=tk.LEFT)
def get_text(x):
    data = json.loads(ftext)
    text1.delete("1.0", "end")
    if x > len(data):
        x = len(data)
    elif x <= 0:
        x = 0
    time=0    
    for i in range(0,x):
        m = random.randint(0,len(data)-1)
        text1.insert('end',data[m]['name']+' 描述：'+data[m]['desc']+'\n'+" 时间："+data[m]['label'][0]+" 难度："+data[m]['label'][1]+'\n')
        time+=int(data[m]['label'][0])
        del data[m]
    text1.insert('end',"共要"+str(time)+"分钟"+'\n')

def search(x):
    data = json.loads(ftext)
    text1.delete("1.0", "end")
    found=False
    for i in range(0,len(data)):
        if x in data[i]["name"]:
            text1.insert('end',data[i]['name']+' 描述：'+data[i]['desc']+'\n'+" 时间："+data[i]['label'][0]+" 难度："+data[i]['label'][1]+'\n')
            found=True
        for j in data[i]["label"]:
            if x in j:
                text1.insert('end',data[i]['name']+' 描述：'+data[i]['desc']+'\n'+" 时间："+data[i]['label'][0]+" 难度："+data[i]['label'][1]+'\n')
                found=True
    if not found:
        text1.insert('end',"亲亲，没有这种题目哦～")

text1=tk.Text(top, fg = 'lightgreen', bg = 'black')
Button1 = tk.Button(frame1,text = '抽取',command = lambda n=n:get_text(n.get()))
Button1.pack(side=tk.LEFT)
Button2 = tk.Button(frame2,text = '搜索',command = lambda m=m:search(m.get()))
Button2.pack(side=tk.LEFT)
text1.pack()
top.mainloop()